///*
// * Created on May 5, 2009
// *
// */
//package org.reactome.cytoscape.v3.internal;
//
//import java.awt.BorderLayout;
//import java.awt.Desktop;
//import java.awt.Dimension;
//import java.awt.FlowLayout;
//import java.awt.Font;
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
//import java.awt.event.MouseAdapter;
//import java.awt.event.MouseEvent;
//import java.io.File;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.Collection;
//import java.util.Collections;
//import java.util.HashMap;
//import java.util.HashSet;
//import java.util.Iterator;
//import java.util.List;
//import java.util.Map;
//import java.util.Set;
//
//import javax.swing.*;
//import javax.swing.border.Border;
//import javax.swing.event.ListSelectionEvent;
//import javax.swing.event.ListSelectionListener;
//
//import org.cytoscape.application.swing.CySwingApplication;
//import org.cytoscape.io.CyFileFilter;
//import org.cytoscape.model.CyColumn;
//import org.cytoscape.model.CyEdge;
//import org.cytoscape.model.CyNetwork;
//import org.cytoscape.model.CyNode;
//import org.cytoscape.model.CyTable;
//import org.cytoscape.view.model.CyNetworkView;
//import org.cytoscape.view.model.View;
//import org.gk.util.ProgressPane;
//import org.reactome.annotate.ModuleGeneSetAnnotation;
//import org.reactome.cancerindex.model.DiseaseData;
//import org.reactome.cancerindex.model.Sentence;
//import org.reactome.funcInt.Interaction;
//import org.reactome.funcInt.ReactomeSource;
//import org.reactome.r3.graph.BreadthFirstSearch;
//import org.reactome.r3.graph.GeneClusterPair;
//import org.reactome.r3.graph.NetworkClusterResult;
//import org.reactome.r3.util.FileUtility;
//import org.reactome.r3.util.InteractionUtilities;
//
//
//
///**
// * A list of actions for the whole network level.
// * @author wgm
// *
// */
//public class NetworkActionCollection {
//    // Used to cache HPRD interactions
////    private Map<String, List<Integer>> fiToPMIDs = null;
//    // Used to help handling attributes
//    private CyAttributesHelper attributesHelper;
//    // Cache this value
//    private ModuleBasedSurvivalAnalysisHelper survivalHelper;
//    private CySwingApplication desktopApp;
//    
//    public NetworkActionCollection(CySwingApplication desktopApp ) {
//	this.desktopApp = desktopApp;
//        attributesHelper = new CyAttributesHelper();
//    }
//    
//    protected Action getLoadCancerGeneIndexAction(final CyNetworkView view) {
//        Action action = new AbstractAction("Load Cancer Gene Index") {
//            public void actionPerformed(ActionEvent e) {
//                loadCancerGeneIndex(view, desktopApp);
//            }
//        };
//        return action;
//    }
//    
//    private void loadCancerGeneIndex(final CyNetworkView view, CySwingApplication desktopApp) {
//        Thread t = new Thread() {
//
//	    private CySwingApplication desktopApp;
//
//	    public void run() {
//                ProgressPane progressPane = new ProgressPane();
//                progressPane.setIndeterminate(true);
//                this.desktopApp.getJFrame().setGlassPane(progressPane);
//                this.desktopApp.getJFrame().getGlassPane().setVisible(true);
//                try {
//                    NCICancerIndexDiseaseHelper diseaseHelper = new NCICancerIndexDiseaseHelper();
//                    if (!diseaseHelper.areDiseasesShown()) {
//                        progressPane.setText("Loading NCI disease terms...");
//                        Map<String, DiseaseData> codeToDisease = diseaseHelper.fetchDiseases();
//                        diseaseHelper.displayDiseases(codeToDisease);
//                    }
//                    // Load gene to diseases
//                    progressPane.setText("Querying gene to diseases mapping...");
//                    Set<String> genes = getGenesInNetwork(view);
//                    RESTFulFIService service = new RESTFulFIService();
//                    Map<String, String> geneToDiseases = service.queryGeneToDisease(genes);
//                    CyAttributesHelper attHelper = new CyAttributesHelper();
//                    attHelper.loadNodeAttributes(view, 
//                                                 "Diseases", 
//                                                 geneToDiseases);
//                }
//                catch(Exception e) {
//                    System.err.println("NetworkActionCollection.loadCancerGeneIndex(): " + e);
//                    e.printStackTrace();
//                    String message = e.getMessage();
//                    String line = message.split("\n")[0];
//                    JOptionPane.showMessageDialog(this.desktopApp.getJFrame(),
//                                                  "Error in loading cancer gene index: " + line,
//                                                  "Error in Loading Cancer Gene Index",
//                                                  JOptionPane.ERROR_MESSAGE);
//                }
//                this.desktopApp.getJFrame().getGlassPane().setVisible(false);
//            }
//        };
//        t.start();
//    }
//    
//    protected Action getRemoveNodesAction(final CyNetworkView view) {
//        Action action = new AbstractAction("Batch Delete") {
//            public void actionPerformed(ActionEvent e) {
//                batchDelete(view, desktopApp);
//            }
//        };
//        return action;
//    }
//    
//    /**
//     * Keep the user provided list of nodes and delete nodes and edge that not in the list.
//     * @param view
//     */
//    private void batchDelete(CyNetworkView view, CySwingApplication desktopApp) {
//	////Fix it. This centers the prompt in the cytoscape window, though it should do it in the
//	//Network view.
//        String input = JOptionPane.showInputDialog(desktopApp.getJFrame(),
//                                                   "Enter a list of nodes separated by \",\" that will be kept:",
//                                                   "Batch Deleting",
//                                                   JOptionPane.QUESTION_MESSAGE);
//        if (input == null || input.trim().length() == 0)
//            return;
//        String[] tokens = input.split(",");
//        Set<String> ids = new HashSet<String>();
//        for (String token : tokens)
//            ids.add(token.trim());
//        List< View<CyNode> > toBeRemoved = new ArrayList< View<CyNode> >();
//        for (Iterator it = view.getEdgeViews().iterator(); it.hasNext();) {
//            View<CyNode> nodeView = (View<CyNode>) it.next();
//            if (!ids.contains(nodeView.getModel().getSUID()))
//                toBeRemoved.add(nodeView);
//        }
//        List <CyEdge> edgesToBeRemoved = new ArrayList<CyEdge>();
//        for (View<CyNode>node:toBeRemoved)
//        {
//            view.getModel().removeEdges(view.getModel().getAdjacentEdgeList(node.getModel(), CyEdge.Type.ANY));
//            view.getModel().removeNodes(Collections.singletonList(node.getModel()));
//        }
//        view.updateView();
//    }
//    
//    protected Action getAddFIsAction(final CyNetworkView view) {
//        Action action = new AbstractAction("Add FIs") {
//            public void actionPerformed(ActionEvent e) {
//                addFIs(view);
//            }
//        };
//        return action;
//    }
//    
//    protected Action getModuleSurvivalAnalysisAction(final CyNetworkView view) {
//        Action action = new AbstractAction("Survival Analysis...") {
//            public void actionPerformed(ActionEvent e) {
//                doModuleSurvivalAnalysis(view);
//            }
//        };
//        return action;
//    }
//    
//    protected Action getAnnotateModuleOnPathwaysActions(final CyNetworkView view) {
//        Action action = new AbstractAction("Pathway Enrichment") {
//            public void actionPerformed(ActionEvent e) {
//                annotateNetworkModules(view, "Pathway", desktopApp);
//            }
//        };
//        return action;
//    }
//    
//    protected Action getAnnotateModuleOnGOCCActions(final CyNetworkView view) {
//        Action action = new AbstractAction("GO Cellular Component") {
//            public void actionPerformed(ActionEvent e) {
//                annotateNetworkModules(view, "CC", desktopApp);
//            }
//        };
//        return action;
//    }
//    
//    protected Action getAnnotateModuleOnGOBPActions(final CyNetworkView view) {
//        Action action = new AbstractAction("GO Biological Process") {
//            public void actionPerformed(ActionEvent e) {
//                annotateNetworkModules(view, "BP", desktopApp);
//            }
//        };
//        return action;
//    }
//    
//    protected Action getAnnotateModuleOnGOMFActions(final CyNetworkView view) {
//        Action action = new AbstractAction("GO Molecular Function") {
//            public void actionPerformed(ActionEvent e) {
//                annotateNetworkModules(view, "MF", desktopApp);
//            }
//        };
//        return action;
//    }
//    
//    protected Action getAnnotateNetworkOnGOCCActions(final CyNetworkView view) {
//        Action action = new AbstractAction("GO Cellular Component") {
//            public void actionPerformed(ActionEvent e) {
//                annotateNetwork(view, "CC");
//            }
//        };
//        return action;
//    }
//    
//    protected Action getAnnotateNetworkOnGOBPActions(final CyNetworkView view) {
//        Action action = new AbstractAction("GO Biological Process") {
//            public void actionPerformed(ActionEvent e) {
//                annotateNetwork(view, "BP");
//            }
//        };
//        return action;
//    }
//    
//    protected Action getAnnotateNetworkOnGOMFActions(final CyNetworkView view) {
//        Action action = new AbstractAction("GO Molecular Function") {
//            public void actionPerformed(ActionEvent e) {
//                annotateNetwork(view, "MF");
//            }
//        };
//        return action;
//    }
//    
//    protected Action getAnnotateNetworkOnPathwayActions(final CyNetworkView view) {
//        Action action = new AbstractAction("Pathway Enrichment") {
//            public void actionPerformed(ActionEvent e) {
//                annotateNetwork(view, "Pathway");
//            }
//        };
//        return action;
//    }
//    
//    private Set<String> getGenesInNetwork(CyNetworkView view) {
//        Set<String> genes = new HashSet<String>();
//        for (Iterator<?> it = view.getEdgeViews().iterator(); it.hasNext();) {
//            View<CyNode> nodeView = (View<CyNode>) it.next();
//            genes.add(nodeView.getModel().getSUID().toString());
//        }
//        return genes;
//    }
//    
//    private void annotateNetwork(final CyNetworkView view,
//                                 final String type) {
//        // Get all genes
//        final Set<String> genes = new HashSet<String>();
//        // Check if there is any linker genes existing
//        Set<String> linkers = new HashSet<String>();
//        CyTable netTable = view.getModel().getDefaultNetworkTable();
//        for (Iterator<?> it = view.getModel().getNodeList().iterator(); it.hasNext();) {
//            //View<CyNode> = (NodeView) it.next();
//            CyNode node = (CyNode) it.next();
//            genes.add(node.getSUID().toString());
//            // Check if this node is a linker
//            Boolean isLinker = (Boolean) node.getNetworkPointer().getDefaultNodeTable().getRow(node.getSUID()).get("IsLinker", Boolean.class);
//
//            if (isLinker != null && isLinker)
//                linkers.add(node.getSUID().toString());
//        }
//        if (linkers.size() > 0) {
//            int reply = JOptionPane.showConfirmDialog(this.desktopApp.getJFrame(), 
//                                                      "Linkers have been used in network construction. Do you want to exclude linkers\n" +
//                                                      "in functional analysis. Choose \"No\" will include linkers, which will bias results.",
//                                                      "Include Linkers?",
//                                                      JOptionPane.YES_NO_CANCEL_OPTION);
//            if (reply == JOptionPane.CANCEL_OPTION)
//                return;
//            if (reply == JOptionPane.YES_OPTION)
//                genes.removeAll(linkers);
//        }
//        Thread t = new Thread() {
//            private CySwingApplication desktopApp;
//
//	    public void run() {
//                ProgressPane progressPane = new ProgressPane();
//                progressPane.setIndeterminate(true);
//                this.desktopApp.getJFrame().setGlassPane(progressPane);
//                progressPane.setText("Annotating the network. Please wait...");
//                this.desktopApp.getJFrame().getGlassPane().setVisible(true);
//                try {
//                    RESTFulFIService fiService = new RESTFulFIService();
//                    List<ModuleGeneSetAnnotation> annotations = fiService.annotateGeneSet(genes,
//                                                                                          type);
//                    displayModuleAnnotations(annotations,
//                                             view,
//                                             type,
//                                             false);
//                }
//                catch(Exception e) {
//                    System.err.println("NetworkActionCollection.annotateNetwork(): " + e);
//                    e.printStackTrace();
//                }
//                progressPane.setIndeterminate(false);
//                this.desktopApp.getJFrame().getGlassPane().setVisible(false);
//            }
//        };
//        t.start();
//    }
//    
//    private void annotateNetworkModules(final CyNetworkView view,
//                                        final String type,
//                                        CySwingApplication desktopApp) {
//        final Map<String, Integer> nodeToModule = extractNodeToModule(view);
//        if (nodeToModule == null || nodeToModule.size() == 0)
//            return;
//        Thread t = new Thread() {
//            public CySwingApplication desktopApp;
//            public void run() {
//                ProgressPane progressPane = new ProgressPane();
//                progressPane.setIndeterminate(true);
//                this.desktopApp.getJFrame().setGlassPane(progressPane);
//                progressPane.setText("Annotating modules. Please wait...");
//                this.desktopApp.getJFrame().getGlassPane().setVisible(true);
//                try {
//                    RESTFulFIService fiService = new RESTFulFIService();
//                    List<ModuleGeneSetAnnotation> annotations = fiService.annotateNetworkModules(nodeToModule,
//                                                                                                 type);
//                    displayModuleAnnotations(annotations,
//                                             view,
//                                             type,
//                                             true);
//                }
//                catch(Exception e) {
//                    System.err.println("NetworkActionCollection.annotateNetworkModules(): " + e);
//                    e.printStackTrace();
//                }
//                progressPane.setIndeterminate(false);
//                this.desktopApp.getJFrame().getGlassPane().setVisible(false);
//            }
//        };
//        t.start();
//    }
//
//    private Map<String, Integer> extractNodeToModule(final CyNetworkView view) {
//	CyTable netTable = view.getModel().getDefaultNetworkTable();
//        // Check if module has been loaded
//	Collection<CyColumn> columns = netTable.getColumns();
//        boolean isFound = false;
//        String attName = "Module";
//        for (CyColumn column : columns) {
//            if (column.getName().equals(attName)) {
//                isFound = true;
//                break;
//            }
//        }
//        if (!isFound) {
//            JOptionPane.showMessageDialog(this.desktopApp.getJFrame(),
//                                          "Please run \"Cluster FI Network\" first in order to annotate modules.",
//                                          "Error in Annotating Modules",
//                                          JOptionPane.ERROR_MESSAGE);
//            return null;
//        }
//        // Recover node to cluster map
//        final Map<String, Integer> nodeToModule = new HashMap<String, Integer>();
//        Set<String> linkers = new HashSet<String>();
//        for (Iterator<?> it = view.getNodeViews().iterator(); it.hasNext();) {
//            View<CyNode> nodeView = (View<CyNode>) it.next();
//            String nodeId = nodeView.getModel().getSUID().toString();
//            Integer module = (Integer) netTable.getRow(nodeView.getModel()).get(attName, Integer.class);
//            // In case there is a null: e.g. an unlinked node should have no module assigned
//            if (module != null)
//            {
//                nodeToModule.put(nodeId, module);
//                //Boolean isLinker = (Boolean) attributes.getAttribute(nodeId, "IsLinker");
//                Boolean isLinker = (Boolean) netTable.getRow(nodeId).get("IsLinker", Boolean.class);
//                if (isLinker != null && isLinker)
//                    linkers.add(nodeId);
//            }
//        }
//        Integer cutoff = applyModuleSizeFilter(nodeToModule);
//        if (cutoff == null)
//            return null; // Have been canceled.
//        if (linkers.size() > 0) {
//            int reply = JOptionPane.showConfirmDialog(this.desktopApp.getJFrame(), 
//                                                      "Linkers have been used in network construction. Do you want to exclude linkers\n" +
//                                                      "in functional analysis. Choose \"No\" will include linkers, which will bias results.",
//                                                      "Include Linkers?",
//                                                      JOptionPane.YES_NO_CANCEL_OPTION);
//            if (reply == JOptionPane.CANCEL_OPTION)
//                return null;
//            if (reply == JOptionPane.YES_OPTION) {
//                nodeToModule.keySet().removeAll(linkers);
//                // Just in case there is nothing left
//                if (nodeToModule.size() == 0) {
//                    JOptionPane.showMessageDialog(this.desktopApp.getJFrame(),
//                                                  "No genes have been left in modules after removing linkers. No annotation can be done!",
//                                                  "Module Annotation", 
//                                                  JOptionPane.INFORMATION_MESSAGE);
//                    return null;
//                }
//            }
//        }
//        return nodeToModule;
//    }
//    
//    private void doModuleSurvivalAnalysis(CyNetworkView view) {
//        Map<String, Integer> nodeToModule = extractNodeToModule(view);
//        if (nodeToModule == null || nodeToModule.size() == 0)
//            return; // No data for analysis
//        String dataType = attributesHelper.getDataSetType(view);
//        if (dataType == null)
//            return; // Don't know a data type. Do nothing!
//        try {
//            if (dataType.equals(CyAttributesHelper.SAMPLE_MUATAION_DATA)) {
//                Map<String, Object> nodeToSamples = attributesHelper.getNodeAttributeValues(view.getModel(), "Samples");
//                if (nodeToSamples == null || nodeToSamples.size() == 0) {
//                    JOptionPane.showMessageDialog(this.desktopApp.getJFrame(),
//                                                  "No sample information has been provided. Survival analysis cannot be done.", 
//                                                  "No Sample Information", 
//                                                  JOptionPane.ERROR_MESSAGE);
//                    return;
//                }
//                Map<String, Set<String>> nodeToSampleSet = extractNodeToSampleSet(nodeToSamples);
//                if (survivalHelper == null)
//                    survivalHelper = new ModuleBasedSurvivalAnalysisHelper();
//                survivalHelper.doSurvivalAnalysis(nodeToModule,
//                                                  nodeToSampleSet);
//                
//            }
//            else if (dataType.equals(CyAttributesHelper.MCL_ARRAY_DATA)) {
//                Map<Integer, Map<String, Double>> moduleToSampleToValue = attributesHelper.getMCLModuleToSampleToValue(view);
//                if (moduleToSampleToValue == null || moduleToSampleToValue.size() == 0) {
//                    JOptionPane.showMessageDialog(this.desktopApp.getJFrame(),
//                                                  "No sample information has been provided. Survival analysis cannot be done.", 
//                                                  "No Sample Information", 
//                                                  JOptionPane.ERROR_MESSAGE);
//                    return;
//                }
//                if (survivalHelper == null)
//                    survivalHelper = new ModuleBasedSurvivalAnalysisHelper();
//                survivalHelper.doSurvivalAnalysisForMCLModules(nodeToModule, 
//                                                               moduleToSampleToValue);
//            }
//        }
//        catch(Exception e) {
//            System.err.println("NetworkActionCollection.doModuleSurvivalAnalysis(): " + e);
//            e.printStackTrace();
//            JOptionPane.showMessageDialog(this.desktopApp.getJFrame(),
//                                          "Error in doing survival analysis: " + e,
//                                          "Error in Survival Analysis",
//                                          JOptionPane.ERROR_MESSAGE);
//        }
//    }
//
//    private Integer applyModuleSizeFilter(final Map<String, Integer> nodeToModule) {
//        Map<Integer, Set<String>> clusterToGenes = new HashMap<Integer, Set<String>>();
//        for (String node : nodeToModule.keySet()) {
//            Integer module = nodeToModule.get(node);
//            InteractionUtilities.addElementToSet(clusterToGenes, module, node);
//        }
//        Set<Integer> values = new HashSet<Integer>();
//        for (Set<String> set : clusterToGenes.values())
//            values.add(set.size());
//        List<Integer> sizeList = new ArrayList<Integer>(values);
//        Collections.sort(sizeList);
//        Integer input = (Integer) JOptionPane.showInputDialog(this.desktopApp.getJFrame(), 
//                                                              "Please choose a size cutoff for modules. Modules with sizes equal\n" +
//                                                              "or more than the cutoff will be used for analysis:", 
//                                                              "Choose Module Size", 
//                                                              JOptionPane.QUESTION_MESSAGE, 
//                                                              null, 
//                                                              sizeList.toArray(), 
//                                                              sizeList.get(0));
//        if (input == null)
//            return null; // Cancel has been pressed.
//        // Do a filtering based on size
//        Set<String> filtered = new HashSet<String>();
//        for (Set<String> set : clusterToGenes.values()) {
//            if (set.size() < input) 
//                filtered.addAll(set);
//        }
//        nodeToModule.keySet().removeAll(filtered);
//        return input;
//    }
////    
////    private void annotateAddedFIs(CyNetworkView view) {
////        // Get edges to be annotated
////        CyAttributes attributes = Cytoscape.getEdgeAttributes();
////        List<Edge> edges = new ArrayList<Edge>();
////        for (Iterator it = view.getEdgeViewsIterator(); it.hasNext();) {
////            EdgeView edgeView = (EdgeView) it.next();
////            Edge edge = edgeView.getEdge();
////            String added = (String) attributes.getAttribute(edge.getIdentifier(), "EDGE_TYPE");
////            if ("FI".equals(added)) {
////                edges.add(edge);
////            }
////        }
////        annotateFIs(view, edges);
////    }
////
////    private void annotateFIs(CyNetworkView view, List<Edge> edges) {
////        NetworkActionHibernateHelper hibernateHelper = new NetworkActionHibernateHelper();
////        hibernateHelper.setAttributeHelper(attributesHelper);
////        hibernateHelper.setDisplayManager(displayManager);
////        hibernateHelper.annotateFIs(edges, view);
////    }
//    
//    private void addFIs(CyNetworkView view) {
//        File[] files = FileUtil.getFiles(view.getComponent(),
//                                         "Add Functional Interactions",
//                                         FileUtil.LOAD,
//                                         new CyFileFilter[]{new CyFileFilter()});
//        if (files == null || files.length == 0)
//            return;
//        try {
//            FileUtility fu = new FileUtility();
//            Set<String> fis = fu.loadInteractions(files[0].getAbsolutePath());
//            CyNetworkGenerator generator = new CyNetworkGenerator();
//            generator.addFIs(fis, view);
//        }
//        catch(IOException e) {
//            e.printStackTrace();
//        }
//    }
//    
//    protected Action getLoadMCLClusters(final CyNetworkView view) {
//        Action action = new AbstractAction("Load MCL Clusters") {
//            public void actionPerformed(ActionEvent e) {
//                loadMCLClusters(view);
//            }
//        };
//        return action;
//    }
//    
//    private void loadMCLClusters(CyNetworkView view) {
//        File[] files = FileUtil.getFiles(view.getComponent(),
//                                         "Load MCL Clusters",
//                                         FileUtil.LOAD,
//                                         new CyFileFilter[]{new CyFileFilter()});
//        if (files == null || files.length == 0)
//            return;
//        try {
//            // Make sure displayed genes are mutated only
//            FileUtility fu = new FileUtility();
//            fu.setInput(files[0].getAbsolutePath());
//            String line = null;
//            Map<String, Integer> idToValue = new HashMap<String, Integer>();
//            int i = 0;
//            while ((line = fu.readLine()) != null) {
//                String[] genes = line.split("\t");
//                for (String gene : genes)
//                    idToValue.put(gene, i);
//                i++;
//            }
//            fu.close();
//            attributesHelper.loadNodeAttributes(view, "MCL_Cluster", idToValue);
//        }
//        catch(IOException e) {
//            CyLogger.getLogger().error(e.getMessage());
//            e.printStackTrace();
//        }
//    }
//    
//    protected Action getFetchInteractionAction(final CyEdge edge) {
//        Action action = new AbstractAction("Query FI Source") {
//            public void actionPerformed(ActionEvent e) {
//                fetchInteraction(edge);
//            }
//        };
//        return action;
//    }
//    
//    private void fetchInteraction(CyEdge edge) {
//        String source = edge.getSource().getSUID().toString();
//        String target = edge.getTarget().getSUID().toString();
//        try {
//            RESTFulFIService fiService = new RESTFulFIService();
//            List<Interaction> interactions = fiService.queryEdge(source, target);
//            // There should be only one reactions
//            if (interactions.size() == 0) {
//                displayMessage("Cannot find interaction for the selected edge!",
//                                "Cannot Find Interaction");
//                return;
//            }
//            displayInteraction(edge, 
//                               interactions);
//        }
//        catch(Exception e) {
//            displayMessage("Exception during querying: please see the error log for detailed information.",
//                           "Eror in Query");
//            e.printStackTrace();
//        }
////        Session session = null;
////        try {
////            SessionFactory sessionFactotry = HibernateUtil.getFISessionFactory();
////            HibernateFIReader fiReader = new HibernateFIReader();
////            fiReader.setSessionFactor(sessionFactotry);
////            session = fiReader.getSessionFactory().openSession();
////            List<Interaction> interactions = fiReader.queryFIsBasedOnGeneNames(source, 
////                                                                               target,
////                                                                               session);
////            // There should be only one reactions
////            if (interactions.size() == 0) {
////                displayMessage("Cannot find interaction for the selected edge!",
////                               "Cannot Find Interaction");
////                return;
////            }
//////            if (interactions.size() > 1) {
//////                displayMessage("Find more than one interaction!",
//////                               "Too Many Interactions");
//////                return;
//////            }
////            displayInteraction(edge, 
////                               interactions);
////            session.close();
////        }
////        catch(Exception e) {
////            displayMessage("Exception during querying: " + e.getMessage(),
////                           "Eror in Query");
////            e.printStackTrace();
////        }
////        if (session != null && session.isOpen())
////            session.close();
//    }
//    
//    private void displayMessage(String message, String title) {
//        JOptionPane.showMessageDialog(this.desktopApp.getJFrame(),
//                                      message,
//                                      title,
//                                      JOptionPane.ERROR_MESSAGE);
//    }
//    
//    private void displayInteraction(CyEdge edge,
//                                    List<Interaction> interactions) {
//        JDialog dialog = new JDialog(this.desktopApp.getJFrame());
//        dialog.setTitle("Interaction Info");
//        dialog.setSize(400, 300);
//        dialog.setLocationRelativeTo(this.desktopApp.getJFrame());
//        JPanel supportPanel = createSupportPane(interactions);
//        dialog.getContentPane().add(supportPanel, BorderLayout.CENTER);
//        // Add a label
//        JLabel label = new JLabel("Interaction: " + edge.getSource().getSUID() + " - " + 
//                                  edge.getTarget().getSUID());
//        // Add an etched border for label
//        Border emptyBorder = BorderFactory.createEmptyBorder(4, 4, 4, 4);
//        Border etchedBorder = BorderFactory.createEtchedBorder();
//        label.setBorder(BorderFactory.createCompoundBorder(etchedBorder, emptyBorder));
//        Font font = label.getFont();
//        label.setFont(font.deriveFont(Font.BOLD));
//        dialog.getContentPane().add(label, BorderLayout.NORTH);
//        dialog.setVisible(true);
//    }
//    
//    private JPanel createSupportPane(List<Interaction> interactions) {
//        JPanel supportPane = new JPanel();
//        supportPane.setBorder(BorderFactory.createEtchedBorder());
//        supportPane.setLayout(new BorderLayout());
//        JTabbedPane supportTabbedPane = new JTabbedPane();
//        // It is possible one pair of FIs in names are from different sources: predicted or
//        // extracted, or several predicted since everything is based on UniProt accession numbers
//        // normalized based on amino acid sequences.
//        List<Interaction> predictedFIs = new ArrayList<Interaction>();
//        List<Interaction> pathwayFIs = new ArrayList<Interaction>();
//        for (Interaction i : interactions) {
//            if (i.getEvidence() == null)
//                pathwayFIs.add(i);
//            else
//                predictedFIs.add(i);
//        }
//        if (pathwayFIs.size() == 0) {
//            // Want to find FIs with highest score
//            Interaction highest = null;
//            for (Interaction i : predictedFIs) {
//                if (highest == null)
//                    highest = i;
//                else if (highest.getEvidence().getProbability() < i.getEvidence().getProbability())
//                    highest = i;
//            }
//            JTable evidenceTable = new JTable();
//            EvidenceTableModel evidenceModel = new EvidenceTableModel();
//            evidenceModel.setEvidence(highest.getEvidence());
//            evidenceTable.setModel(evidenceModel);
//            supportTabbedPane.addTab("Support Evidence",
//                                     new JScrollPane(evidenceTable));
//        }
//        else {
//            // Only pathway FIs possible
//            Set<ReactomeSource> allSources = new HashSet<ReactomeSource>();
//            for (Interaction interaction : pathwayFIs)
//                allSources.addAll(interaction.getReactomeSources());
//            setReactomeSourceTab(supportTabbedPane, allSources);
//        }
//        supportPane.add(supportTabbedPane, BorderLayout.CENTER);
//        return supportPane;
//    }
//
//    private void setReactomeSourceTab(JTabbedPane supportTabbedPane,
//                                      Set<ReactomeSource> sources) {
//        final JTable sourceTable = new JTable();
//        sourceTable.addMouseListener(new MouseAdapter() {
//            public void mousePressed(MouseEvent e) {
//                if (e.isPopupTrigger()) 
//                    doSourceTablePopup(sourceTable, e);
//                else if (e.getClickCount() == 2) {
//                    showReactomeSource(sourceTable);
//                }
//            }
//            public void mouseReleased(MouseEvent e) {
//                if (e.isPopupTrigger())
//                    doSourceTablePopup(sourceTable, e);
//            }
//        });
//        sourceTable.setToolTipText("Double click or right clik to use popup menu for details");
//        ReactomeSourceTableModel sourceModel = new ReactomeSourceTableModel();
//        sourceModel.setReactomeSources(sources);
//        sourceTable.setModel(sourceModel);
//        supportTabbedPane.addTab("Reactome Sources",
//                                 new JScrollPane(sourceTable));
//    }
//    
//
//    private void showReactomeSource(final JTable table) {
//        // Work for one selection only
//        int selectedRow = table.getSelectedRow();
//        if (selectedRow < 0)
//            return;
//        ReactomeSourceTableModel tableModel = (ReactomeSourceTableModel) table.getModel();
//        Long id = (Long) tableModel.getValueAt(selectedRow, 0);
//        String dataSourceURL = PlugInScopeObjectManager.getManager().getDataSourceURL();
//        if (dataSourceURL == null) {
//            displayMessage("Data source URL has not been set.", 
//                           "Error");
//        }
//        Desktop.getDesktop().browse(java.net.URI.create(dataSourceURL + id));
////        try {
////            //String url = "http://brie8.cshl.edu/cgi-bin/instancebrowser?DB=test_reactome_28_plus_i&ID=" + id;
////            //displayURL(url, this.desktopApp.getJFrame());
////            displayManager.showInstance(id);
////        }
////        catch(Exception e1) {
////            displayMessage("Cannot open the web page for " + id  + ": " + e1.getMessage(), 
////            "Error");
////        }
//    }
//    
//    private void doSourceTablePopup(final JTable table, 
//                                    MouseEvent e) {
//        // Work for one selection only
//        final int selectedRow = table.getSelectedRow();
//        if (selectedRow < 0)
//            return;
//        JPopupMenu popup = new JPopupMenu();
//        JMenuItem goToReactome = new JMenuItem("Open Reactome Source");
//        goToReactome.addActionListener(new ActionListener() {
//            public void actionPerformed(ActionEvent e) {
//                showReactomeSource(table);
//            }
//        });
//        popup.add(goToReactome);
//        popup.show(table, e.getX(), e.getY());
//    }
//    
//    protected Action getLoadHitGenesAction(final CyNetworkView view) {
//        Action loadHitGeneAction = new AbstractAction("Load Hit Genes") {
//            public void actionPerformed(ActionEvent e) {
//                loadHitGenes(view);
//            }
//        };
//        return loadHitGeneAction;
//    }
//    
//    protected Action getSelectNodesAction(final CyNetworkView view) {
//        Action selectNodesAction = new AbstractAction("Select Nodes") {
//            public void actionPerformed(ActionEvent e) {
//                selectNodes(view);
//            }
//        };
//        return selectNodesAction;
//    }
//    
////    protected Action getLoadPathwayAction() {
////        Action loadPathwayAction = new AbstractAction("Load Pathway Action") {
////            public void actionPerformed(ActionEvent e) {
////                loadPathway();
////            }
////        };
////        return loadPathwayAction;
//////    }
////    
////    private void loadPathway() {
////        String input = JOptionPane.showInputDialog(this.desktopApp.getJFrame(),
////                                                   "Enter DB_ID for the pathway");
////        if (input == null)
////            return;
////        try {
////            MySQLAdaptor dba = PlugInScopeObjectManager.getManager().getSourceDBA();
////            GKInstance pathway = dba.fetchInstance(new Long(input));
////            if (pathway == null ||
////                !pathway.getSchemClass().isa(ReactomeJavaConstants.Pathway)) {
////                JOptionPane.showMessageDialog(this.desktopApp.getJFrame(),
////                                              "The enter DB_ID is not a valid pathway id: " + input,
////                                              "Error in Pathway ID",
////                                              JOptionPane.ERROR_MESSAGE);
////                return;
////            }
////            CyNetworkGenerator networkGenerator = new CyNetworkGenerator();
////            CyNetwork network = networkGenerator.convertToNetwork(pathway);
////        }
////        catch(Exception e) {
////            System.err.println("NeworkActionCollection.loadPathway(): " + e);
////            e.printStackTrace();
////        }
////    }
//    
//    protected Action getLoadGeneExpAction(final CyNetworkView view) {
//        Action loadGeneExpAction = new AbstractAction("Load Gene Exp") {
//            public void actionPerformed(ActionEvent e) {
//                loadGeneExpression(view);
//            }
//        };
//        return loadGeneExpAction;
//    }
//    
//    protected Action getLoadMutationAction(final CyNetworkView view) {
//        Action loadMutationAction = new AbstractAction("Load Mutation") {
//            public void actionPerformed(ActionEvent e) {
//                loadMutations(view);
//            }
//        };
//        return loadMutationAction;
//    }
//    
//    protected Action getLoadConnectionDegreeAction(final CyNetworkView view) {
//        Action loadConnectionDegreeAction = new AbstractAction("Load Connection Degree") {
//            public void actionPerformed(ActionEvent e) {
//                loadConnectionDegree(view);
//            }
//        };
//        return loadConnectionDegreeAction;
//    }
//    
//    protected Action getFetchCGIAnnotations(final CyNetworkView view,
//                                            final View<CyNode> nodeView) {
//        Action action = new AbstractAction("Fetch Cancer Gene Index") {
//            public void actionPerformed(ActionEvent e) {
//                fetchCGIAnnotations(view, nodeView);
//            }
//        };
//        return action;
//    }
//    
//    private void fetchCGIAnnotations(CyNetworkView view,
//                                     final View<CyNode> nodeView) {
//        // Work on another thread to avoid delay in the main window
//        Thread t = new Thread() {
//            public void run() {
//                try {
//                    RESTFulFIService service = new RESTFulFIService();
//                    List<Sentence> sentences = service.queryCGIAnnotations(nodeView.getModel().getSUID().toString());
//                    displayCGISentences(nodeView, 
//                                        sentences);
//                }
//                catch(Exception e) {
//                    System.err.println("NetworkActionCollection.fetchCGIAnnotations(): " + e);
//                    e.printStackTrace();
//                    displayMessage("Error in querying cancer gene index annotations for " + 
//                                   nodeView.getModel().getSUID() + ": " + e.getMessage(),
//                    "Error in Querying");
//                }
//            }
//        };
//        t.start();
//    }
//    
//    private synchronized void displayCGISentences(View<CyNode> nodeView,
//                                     List<Sentence> sentences) {
//        String gene = nodeView.getModel().getSUID().toString();
//        if (sentences == null || sentences.size() == 0) {
//            displayMessage("Cannot find any cancer gene index annotation for \"" + gene + "\".",
//                           "No Annotation");
//            return;
//        }
//        CancerIndexSentenceDisplayFrame cgiFrame = PlugInScopeObjectManager.getManager().getCancerIndexFrame(desktopApp);
//        cgiFrame.display(sentences, gene);
//    }
//    
//    protected Action getFetchFIsForNodeAction(final CyNetworkView networkView,
//                                              final View<CyNode> nodeView) {
//        Action fetchFIsAction = new AbstractAction("Fetch FIs") {
//            
//            public void actionPerformed(ActionEvent e) {
//                fetchFIsForNode(networkView,
//                                nodeView);
//            }
//        };
//        return fetchFIsAction;
//    }
//    
//    private void fetchFIsForNode(CyNetworkView networkView,
//                                 View<CyNode> nodeView) {
//        // Get the id first for the view
//        String name = nodeView.getModel().getSUID().toString();
//        try {
//            RESTFulFIService fiService = new RESTFulFIService();
//            Set<String> fiPartners = fiService.queryFIsForNode(name);
//            // There should be only one reactions
//            if (fiPartners.size() == 0) {
//                displayMessage("Cannot find interaction for " + name + "!",
//                                "Cannot Find Interaction");
//                return;
//            }
//            displayNodeFIs(name, 
//                           fiPartners,
//                           networkView);
//        }
//        catch(Exception e) {
//            displayMessage("Exception during querying: please see the error log for detailed information.",
//                           "Eror in Query");
//            e.printStackTrace();
//        }
//    }
//    
//    private void splitPartners(Set<String> partners,
//                               List<String> partnersInNetwork,
//                               List<String> partnersNotInNetwork,
//                               CyNetworkView networkView) {
//        Set<String> displayed = new HashSet<String>();
//        for (Iterator<?> it = networkView.getModel().getNodeList().iterator(); it.hasNext();) {
//            CyNode node = (CyNode) it.next();
//            displayed.add(node.getSUID().toString());
//        }
//        for (String partner : partners) {
//            if (displayed.contains(partner))
//                partnersInNetwork.add(partner);
//            else
//                partnersNotInNetwork.add(partner);
//        }
//        Collections.sort(partnersInNetwork);
//        Collections.sort(partnersNotInNetwork);
//    }
//    
//    private void displayNodeFIs(final String name,
//                                Set<String> partners,
//                                final CyNetworkView networkView) {
//        FIPartnersDialog dialog = new FIPartnersDialog(name, 
//                                                       partners,
//                                                       networkView);
//        dialog.setSize(400, 300);
//        dialog.setLocationRelativeTo(this.desktopApp.getJFrame());
//        dialog.setModal(true);
//        dialog.setVisible(true);
//    }
//    
//    protected Action getAnnotateFIAction(final CyNetworkView view) {
//        Action annotateFIAction = new AbstractAction("Fetch FI Annotations") {
//            public void actionPerformed(ActionEvent e) {
//                //annotateFIs(view);
//                annotateFIsViaWS(view);
//            }
//        };
//        return annotateFIAction;
//    }
//    
//    protected Action getNetworkClusterAction(final CyNetworkView view) {
//        Action networkClusterAction = new AbstractAction("Cluster FI Network") {
//            public void actionPerformed(ActionEvent e) {
//                clusterFINetwork(view);
//            }
//        };
//        return networkClusterAction;
//    }
//    
//    private void clusterFINetwork(final CyNetworkView view) {
//        String clusteringType = attributesHelper.getClusteringType(view);
//        if (clusteringType != null && !CyAttributesHelper.SPECTRA_PARTITION_CLUSTERING.equals(clusteringType)) {
//            int reply = JOptionPane.showConfirmDialog(this.desktopApp.getJFrame(), 
//                                                      "The displayed network has been clustered before using a different algorithm.\n" +
//                                                      "You may get different clustering results using this clustering feature. Do\n" +
//                                                      "you want to continue?", 
//                                                      "Clustering Algorithm Warning", 
//                                                      JOptionPane.OK_CANCEL_OPTION);
//            if (reply != JOptionPane.OK_OPTION)
//                return;
//        }
//        Thread t = new Thread() {
//            private CySwingApplication desktopApp;
//
//	    public void run(CySwingApplication desktopApp) {
//                ProgressPane progressPane = new ProgressPane();
//                progressPane.setIndeterminate(true);
//                this.desktopApp.getJFrame().setGlassPane(progressPane);
//                progressPane.setText("Clustering FI network. Please wait...");
//                this.desktopApp.getJFrame().getGlassPane().setVisible(true);
//                List<CyEdge> edges = new ArrayList<CyEdge>();
//                for (Iterator<?> it = view.getEdgeViews().iterator(); it.hasNext();) {
//                    View<CyEdge> edgeView = (View<CyEdge>) it.next();
//                    CyEdge edge = edgeView.getModel();
//                    edges.add(edge);
//                };
//                try {
//                    RESTFulFIService service = new RESTFulFIService();
//                    NetworkClusterResult clusterResult = service.cluster(edges);
//                    Map<String, Integer> nodeToCluster = new HashMap<String, Integer>();
//                    List<GeneClusterPair> geneClusterPairs = clusterResult.getGeneClusterPairs();
//                    if (geneClusterPairs != null) {
//                        for (GeneClusterPair geneCluster : geneClusterPairs)
//                            nodeToCluster.put(geneCluster.getGeneId(),
//                                              geneCluster.getCluster());
//                    }
//                    attributesHelper.loadNodeAttributes(view, "Module", nodeToCluster);
//                    attributesHelper.storeClusteringType(view, CyAttributesHelper.SPECTRA_PARTITION_CLUSTERING);
//                    Map<String, Object> nodeToSamples = attributesHelper.getNodeAttributeValues(view.getNetwork(), 
//                                                                                                  "Samples");
//                    //loadEdgeAttributes(view, "FI Score", edgeToScore);
//                    showModuleInTab(nodeToCluster, 
//                                    nodeToSamples,
//                                    clusterResult.getModularity(),
//                                    view);
//                }
//                catch(Exception e) {
//                    System.err.println("NetworkActionCollection.annotateFIs(): " + e);
//                    e.printStackTrace();
//                    JOptionPane.showMessageDialog(this.desktopApp.getJFrame(),
//                                                  // Since the error message is ususally too long.
//                                                  // Use the following instead
//                                                  "Error in annotating: check the logging information for detailed errors.",
//                                                  "Error in Annotating", 
//                                                  JOptionPane.ERROR_MESSAGE);
//                }
//                progressPane.setIndeterminate(false);
//                this.desktopApp.getJFrame().getGlassPane().setVisible(false);
//            }
//        };
//        t.start();
//    }
//    
//    /**
//     * Show modules in tab.
//     * @param nodeToCluster
//     * @param view
//     */
//    private void showModuleInTab(Map<String, Integer> nodeToCluster,
//                                 Map<String, Object> nodeToSamples,
//                                 Double modularity,
//                                 CyNetworkView view) {
//        Map<String, Set<String>> nodeToSampleSet = extractNodeToSampleSet(nodeToSamples);
//        ResultDisplayHelper.getHelper().showModuleInTab(nodeToCluster, 
//                                                        nodeToSampleSet,
//                                                        modularity, 
//                                                        view);
//    }
//
//    private Map<String, Set<String>> extractNodeToSampleSet(Map<String, Object> nodeToSamples) {
//        Map<String, Set<String>> nodeToSampleSet = null;
//        if (nodeToSamples != null) {
//            nodeToSampleSet = new HashMap<String, Set<String>>();
//            for (String node : nodeToSamples.keySet()) {
//                String sampleText = (String) nodeToSamples.get(node);
//                String[] tokens = sampleText.split(";");
//                Set<String> set = new HashSet<String>();
//                for (String token : tokens)
//                    set.add(token);
//                nodeToSampleSet.put(node, set);
//            }
//        }
//        return nodeToSampleSet;
//    }
//    
//    private void displayModuleAnnotations(List<ModuleGeneSetAnnotation> annotations,
//                                          CyNetworkView view,
//                                          String type,
//                                          boolean isForModule) {
//        ResultDisplayHelper.getHelper().displayModuleAnnotations(annotations, 
//                                                                 view, 
//                                                                 type, 
//                                                                 isForModule);
//    }
//    
//    private void annotateFIsViaWS(final CyNetworkView view) {
//        Thread t = new Thread() {
//            public void run() {
//                ProgressPane progressPane = new ProgressPane();
//                progressPane.setIndeterminate(true);
//                this.desktopApp.getJFrame().setGlassPane(progressPane);
//                progressPane.setText("Annotating FIs. Please wait...");
//                this.desktopApp.getJFrame().getGlassPane().setVisible(true);
//                try {
//                    RESTFulFIService service = new RESTFulFIService();
//                    new FIAnnotationHelper(desktopApp).annotateFIs(view, 
//                                                         service,
//                                                         attributesHelper);
//                }
//                catch(Exception e) {
//                    System.err.println("NetworkActionCollection.annotateFIs(): " + e);
//                    e.printStackTrace();
//                    JOptionPane.showMessageDialog(this.desktopApp.getJFrame(),
//                                                  "Error in annotating: see the error log for details.",
//                                                  "Error in Annotating", 
//                                                  JOptionPane.ERROR_MESSAGE);
//                }
//                progressPane.setIndeterminate(false);
//                this.desktopApp.getJFrame().getGlassPane().setVisible(false);
//            }
//        };
//        t.start();
//    }
//    
////    private void annotateFIs(CyNetworkView view) {
////        List<Edge> edges = new ArrayList<Edge>();
////        for (Iterator it = view.getEdgeViewsIterator(); it.hasNext();) {
////            EdgeView edgeView = (EdgeView) it.next();
////            Edge edge = edgeView.getEdge();
////            edges.add(edge);
////        };
////        annotateFIs(view, edges);
////    }
//    
//    private void loadGeneExpression(CyNetworkView view) {
//        File[] files = FileUtil.getFiles(view.getComponent(),
//                                         "Load Gene Expression",
//                                         FileUtil.LOAD,
//                                         new CyFileFilter[]{new CyFileFilter()});
//        if (files == null || files.length == 0)
//            return;
//        try {
//            FileUtility fu = new FileUtility();
//            fu.setInput(files[0].getAbsolutePath());
//            String line = fu.readLine();
//            Map<String, Double> geneToTValue = new HashMap<String, Double>();
//            Map<String, Double> geneToPvalue = new HashMap<String, Double>();
//            while ((line = fu.readLine()) != null) {
//                String[] tokens = line.split("\t");
//                Double tvalue = new Double(tokens[1]);
//                Double pvalue = new Double(tokens[2]);
//                geneToTValue.put(tokens[0], tvalue);
//                geneToPvalue.put(tokens[0], pvalue);
//            }
//            fu.close();
//            attributesHelper.loadNodeAttributes(view, "GeneExpressionTValue", geneToTValue);
//            attributesHelper.loadNodeAttributes(view, "GeneExpressionPValue", geneToPvalue);
//        }
//        catch(IOException e) {
//            CyLogger.getLogger().error(e.getMessage());
//            e.printStackTrace();
//        }
//    }
//    
//    private void loadConnectionDegree(final CyNetworkView view) {
//        File[] files = FileUtil.getFiles(view.getComponent(),
//                                         "Load Connection Degree",
//                                         FileUtil.LOAD,
//                                         new CyFileFilter[]{new CyFileFilter()});
//        if (files == null || files.length == 0)
//            return;
//        try {
//            // Make sure displayed genes are mutated only
//            FileUtility fu = new FileUtility();
//            Set<String> fis = fu.loadInteractions(files[0].getAbsolutePath());
//            BreadthFirstSearch bfs = new BreadthFirstSearch();
//            Map<String, Set<String>> geneToPartners = bfs.generateIdToPartnersMap(fis);
//            Map<String, Integer> idToValue = new HashMap<String, Integer>();
//            for (String gene : geneToPartners.keySet()) {
//                Set<String> partners = geneToPartners.get(gene);
//                //partners.retainAll(mutatedGenes);
//                idToValue.put(gene, partners.size());
//            }
//            attributesHelper.loadNodeAttributes(view, "connectionDegree", idToValue);
//        }
//        catch(IOException e) {
//            CyLogger.getLogger().error(e.getMessage());
//            e.printStackTrace();
//        }
//    }
//    
//    private void loadMutations(final CyNetworkView view) {
//        File[] files = FileUtil.getFiles(view.getComponent(),
//                                         "Load Mutation Count",
//                                         FileUtil.LOAD,
//                                         new CyFileFilter[]{new CyFileFilter()});
//        if (files == null || files.length == 0)
//            return;
//        try {        
//            Map<String, Integer> geneToCount = new HashMap<String, Integer>();
//            FileUtility fu = new FileUtility();
//            fu.setInput(files[0].getAbsolutePath());
//            String line = fu.readLine();
//            while ((line = fu.readLine()) != null) {
//                String[] tokens = line.split("\t");
//                String gene = tokens[0];
//                Integer count = new Integer(tokens[1]);
//                geneToCount.put(gene, count);
//            }
//            fu.close();
//            attributesHelper.loadNodeAttributes(view, "mutationNumber", geneToCount);
//        }
//        catch(IOException e1) {
//            CyLogger.getLogger().error(e1.getMessage());
//            e1.printStackTrace();
//        }
//    }
//    
//    private void loadHitGenes(CyNetworkView view) {
//        File[] files = FileUtil.getFiles(view.getComponent(),
//                                         "Load List of Genes",
//                                         FileUtil.LOAD,
//                                         new CyFileFilter[]{new CyFileFilter()});
//        if (files == null || files.length == 0)
//            return;
//        try {        
//            FileUtility fu = new FileUtility();
//            Set<String> hits = fu.loadInteractions(files[0].getAbsolutePath());
//            Map<String, String> geneToValue = new HashMap<String, String>();
//            for (String hit : hits)
//                geneToValue.put(hit, Boolean.TRUE.toString());
//            attributesHelper.loadNodeAttributes(view, "IS_HIT_GENE", geneToValue);
//        }
//        catch(IOException e1) {
//            CyLogger.getLogger().error(e1.getMessage());
//            e1.printStackTrace();
//        }
//    }
//
//    private void selectNodes(CyNetworkView view) {
//        String input = JOptionPane.showInputDialog(view.getComponent(),
//                                                   "Enter a list of nodes separated by \",\":",
//                                                   "Search for Nodes",
//                                                   JOptionPane.QUESTION_MESSAGE);
//        if (input == null || input.trim().length() == 0)
//            return;
//        String[] tokens = input.split(",");
//        Set<String> ids = new HashSet<String>();
//        for (String token : tokens)
//            ids.add(token.trim());
//        List<CyNode> selected = new ArrayList<CyNode>();
//        for (Iterator it = view.getNodeViews().iterator(); it.hasNext();) {
//           View<CyNode> node = (View<CyNode>) it.next();
//            if (ids.contains(node.getModel().getSUID().toString()))
//                selected.add(node.getModel());
//        }
//        //view.getModel().setSelectedNodeState(selected, true);
//        for (CyNode node: selected)
//            view.getModel().getRow(node).set(view.getModel().SELECTED, true);
//        view.updateView();
//    }
//    
//    private class FIPartnersDialog extends JDialog {
//        private JLabel inLabel;
//        private JLabel outLabel;
//        private JList inList;
//        private JList outList;
//        private List<String> partnersInNetwork;
//        private List<String> partnersNotInNetwork;
//        private JButton addPartnersBtn;
//        private static CySwingApplication desktopApp;
//        
//        public FIPartnersDialog(String name,
//                                Set<String> partners,
//                                CyNetworkView networkView) {
//            super(desktopApp.getJFrame());
//            init(name, partners, networkView);
//        }
//        
//        private void init(final String name,
//                          Set<String> partners,
//                          final CyNetworkView networkView) {
//            // Create a dialog to display FI partners
//            JPanel contentPane = new JPanel();
//            contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
//            JLabel label = new JLabel();
//            label.setText("Total FI parnters for \"" + name + "\": " + partners.size());
//            contentPane.add(label);
//            partnersInNetwork = new ArrayList<String>();
//            partnersNotInNetwork = new ArrayList<String>();
//            splitPartners(partners,
//                          partnersInNetwork,
//                          partnersNotInNetwork, 
//                          networkView);
//            contentPane.add(Box.createVerticalStrut(6));
//            // List partners in networks already
//            inLabel = new JLabel("Partners in network: " + partnersInNetwork.size());
//            contentPane.add(inLabel);
//            if (partnersInNetwork.size() > 0) {
//                inList = new JList();
//                DefaultListModel model = new DefaultListModel();
//                for (String id : partnersInNetwork)
//                    model.addElement(id);
//                inList.setModel(model);
//                inList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
//                inList.setVisibleRowCount(-1);
//                inList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//                JScrollPane listScroller = new JScrollPane(inList);
//                listScroller.setPreferredSize(new Dimension(300, 40));
//                listScroller.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
//                contentPane.add(listScroller);
//            }
//            contentPane.add(Box.createVerticalStrut(6));
//            outLabel = new JLabel("Partners not in network: " + partnersNotInNetwork.size());
//            contentPane.add(outLabel);
//            if (partnersNotInNetwork.size() > 0) {
//                outList = new JList();
//                DefaultListModel model = new DefaultListModel();
//                for (String id : partnersNotInNetwork)
//                    model.addElement(id);
//                outList.setModel(model);
//                outList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
//                outList.setVisibleRowCount(-1);
//                JScrollPane listScroller = new JScrollPane(outList);
//                listScroller.setPreferredSize(new Dimension(300, 40));
//                listScroller.setAlignmentX(JScrollPane.LEFT_ALIGNMENT);
//                contentPane.add(listScroller);
//                final JButton addPartnersBtn = new JButton("Add selected partner(s) to network");
//                contentPane.add(addPartnersBtn);
//                addPartnersBtn.setEnabled(false);
//                outList.addListSelectionListener(new ListSelectionListener() {
//                    public void valueChanged(ListSelectionEvent e) {
//                        if (outList.getSelectedValue() != null)
//                            addPartnersBtn.setEnabled(true);
//                        else
//                            addPartnersBtn.setEnabled(false);
//                    }
//                });
//                addPartnersBtn.addActionListener(new ActionListener() {
//                    public void actionPerformed(ActionEvent e) {
//                        addSelectedPartnersToNetwork(name, networkView);
//                    }
//                });
//            }
//            
//            JPanel controlPane = new JPanel();
//            controlPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
//            JButton closeBtn = new JButton("Close");
//            controlPane.add(closeBtn);
//            setTitle("FI Partners for " + name);
//            getContentPane().add(contentPane, BorderLayout.CENTER);
//            Border border = BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(),
//                                                               BorderFactory.createEmptyBorder(8, 8, 8, 8));
//            contentPane.setBorder(border);
//            getContentPane().add(controlPane, BorderLayout.SOUTH);
//            controlPane.setBorder(BorderFactory.createEtchedBorder());
//            closeBtn.addActionListener(new ActionListener() {
//                public void actionPerformed(ActionEvent e) {
//                    dispose();
//                }
//            });
//        }
//        
//        private void addSelectedPartnersToNetwork(String name,
//                                                  CyNetworkView networkView) {
//            CyNetworkGenerator generator = new CyNetworkGenerator();
//            Set<String> partners = new HashSet<String>();
//            Object[] selected = outList.getSelectedValues();
//            for (Object s : selected)
//                partners.add(s.toString());
//            generator.addFIPartners(name, 
//                                    partners, 
//                                    networkView);
//            // Need to add FIs between newly added nodes and existing nodes
//            Set<String> existing = new HashSet<String>();
//            for (Iterator<?> it = networkView.getModel().getNodeList().iterator(); it.hasNext();) {
//                CyNode node = (CyNode) it.next();
//                existing.add(node.getSUID().toString());
//            } 
//            //Need to check mutal FIs
//            //existing.removeAll(partners);
//            existing.remove(name);
//            RESTFulFIService fiService = new RESTFulFIService();
//            try {
//                Set<String> interactions = fiService.queryFIsBetween(partners,
//                                                                     existing);
//                generator.addFIs(interactions, networkView);
//            }
//            catch(Exception e) {
//                System.err.println("NetworkActionCollection.addSelectedPartnersToNetwork(): " + e);
//                e.printStackTrace();
//                JOptionPane.showMessageDialog(this.desktopApp.getJFrame(),
//                                              "Cannot fetch FIs between newly added nodes and existing nodes: see error log for details.",
//                                              "Error in Fetching FIs",
//                                              JOptionPane.ERROR_MESSAGE);
//            }
//            // Need to update labels and two lists
//            partnersNotInNetwork.removeAll(partners);
//            partnersInNetwork.addAll(partners);
//            Collections.sort(partnersNotInNetwork);
//            Collections.sort(partnersInNetwork);
//            updateAllUIs();
//        }
//        
//        private void updateAllUIs() {
//            inLabel.setText("Partners in network: " + partnersInNetwork.size());
//            inList.clearSelection();
//            DefaultListModel model = (DefaultListModel) inList.getModel();
//            model.removeAllElements();
//            for (String id : partnersInNetwork)
//                model.addElement(id);
//            outLabel.setText("Partners not in network: " + partnersNotInNetwork.size());
//            if (outList != null) {
//                outList.clearSelection();
//                model = (DefaultListModel) outList.getModel();
//                model.removeAllElements();
//                for (String id : partnersNotInNetwork)
//                    model.addElement(id);
//                if (addPartnersBtn != null)
//                    addPartnersBtn.setEnabled(false);
//            }
//        }
//        
//    }
//}
